<?php

class Ext_Application_Resource_Config extends Zend_Application_Resource_ResourceAbstract
{
    const DEFAULT_REGISTRY_KEY = 'config';

    protected $_registryKey;

    protected $_config;

    public function init()
    {
        $options = $this->getOptions();

        $this->_registryKey = self::DEFAULT_REGISTRY_KEY;
        if ( isset($options['registry_key']) && !is_numeric($options['registry_key'])) {
            $this->_registryKey = $options['registry_key'];
        }
        unset( $options['registry_key'] );

        $paths = isset( $options['path'] )
        ? $options['path']
        : array();
        if ( ! is_array( $paths ) ) {
            $configFiles = array( $paths );
        }
        unset( $options['path'] );
        if ( empty( $paths ) ) {
            $paths = array("");
        }


        if ( ! isset( $options['config'] ) ) {
            return $this;
        }
        $configFiles = $options['config'];
        if ( ! is_array( $configFiles ) ) {
            $configFiles = array( $configFiles );
        }
        unset( $options['config'] );

        if (Zend_Registry::isRegistered( $this->_registryKey )) {
            $this->_config = Zend_Registry::get( $this->_registryKey );
        } else {
            $this->_config = new Zend_Config( array(), true );
        }
        if ( !empty( $options ) ) {
            $newConfig = new Zend_Config( $options, true );
            $this->_config->merge( $newConfig );
        }

        foreach ( $configFiles as $configFile ) {
            foreach ( $paths as $path ) {
                if ( Zend_Loader::isReadable( $path . DIRECTORY_SEPARATOR . $configFile ) ) {
                    $newConfig = new Zend_Config_Ini( $path . DIRECTORY_SEPARATOR . $configFile, null, true );
                    $this->_config->merge( $newConfig );
                }
            }
        }
//        print_r($this->_config);exit;
        Zend_Registry::set( $this->_registryKey , $this->_config );
        return $this->_config;
    }

    public function getRegistryKey() {
        return $this->_registryKey;
    }

    public function getConfig() {
        return $this->_config;
    }
}
